/* eslint-disable */
import * as accountsReceivableService from '../../services/credit/accountsReceivableService';
import * as homeService from '../../services/home/homeService';
import { message } from "antd";
import config from '../../config/config';
import { history } from 'umi';

export default {
  namespace: "accountsReceivableModel",
  state: {
    accountsReceivableLoading: false,
    accountsReceivableList: [],
    total: 0,
    currentPage: 1,
    pageSize: config.PAGE_SIZE,
    operateType: '',
    accountsReceivableInfoData: null,
    selectedRows: [],
    selectedRowKeys: [],
    selectedItemRowCode: "",
    selectedItemRowName: "",
    searchParams: { isCancel: "1" },
    modalType: "item",

    showDictRow: null,
    counterpartyModalVisible: false,
    counterpartyLoading: false,
    counterpartyList: [],
    counterpartyCurrentPage: 0,
    counterpartyPageSize: config.PAGE_SIZE,
    counterpartyTotal: 0,
    selectedValueRows: [],
    selectedValueRowKeys: [],

    accountsReceivableModalVisible: false,
    accountsReceivableModalLoading: false,
    accountsReceivableModalList: [],
    accountsReceivableModalCurrentPage: 0,
    accountsReceivableModalPageSize: config.PAGE_SIZE,
    accountsReceivableModalTotal: 0,
    selectedValueRows: [],
    selectedValueRowKeys: [],

    ownershipInstitution: [],
    countNodeList: [],
    modelList: {},
    modelFlag: false,
    counterpartyModalFlag: false,
    examinationApprovalStatus: [],
    historicalAssessmentResultsList: [],
    adjustmentEvaluationResultsList: [],

    accountsReceivableNum: 0,
    withinTimeLimitNum: 0,
    cancelAfterVerification: 0,
    allNum: 0,

    menuData: [],
    overdueTypeList: [],
    overdueReasonList: [],
    personalizedColumn: [],
    allData: [],
    treeColumns: [
      { title: '归属机构', key: 'affiliatedInstitutionName', },
      { title: '出库通知单号', key: 'outboundOrderNumber', },
      { title: '销售订单号', key: 'sourcePrimaryKey', },
      { title: '交易方名称', key: 'counterpartyName', },
      { title: '主数据编码', key: 'masterDataEncoding', },
      { title: '邓白氏编码', key: 'dunsCode', },
      { title: '交货单创建时间', key: 'deliveryOrderCreateTime', },
      { title: '发货过账时间', key: 'outboundTime', },
      { title: '发货金额', key: 'totalPrice', },
      { title: '开票时间', key: 'invoiceTime', },
      { title: '开票金额', key: 'creditAmount', },
      { title: '应收金额', key: 'actuallyTake', },
      { title: '回款金额', key: 'cancelAmount', },
      { title: '交易币种', key: 'currency', },
      { title: '起算节点', key: 'countNodeName', },
      { title: '支付比例（%）', key: 'paymentRatio', },
      { title: '账期', key: 'paymentDays', },
      { title: '账期起算日', key: 'paymentDaysZeroDate', },
      { title: '到期日', key: 'maturityDate', },
      { title: '是否逾期', key: 'isOverdue', },
      { title: '逾期天数', key: 'overDueDay', },
      { title: '是否回款', key: 'isCancel', },
      { title: '调整原因', key: 'lateReason', },
      { title: '业务员', key: 'businessPeopleName', },
    ],
    attachmentUploadModalVisible: false,
    attachmentUploadModalList: [],
    attachmentUploadModalLoading: false,
    masterDataCode: null,
  },

  reducers: {
    updateState(state, { payload }) {
      return { ...state, ...payload }
    },
  },

  effects: {
    *init({ payload: { history } }, { select, call, put }) {
      let { pageUrl, userInfo } = yield select(state => state.globalModel);
      let { treeColumns } = yield select(state => state.accountsReceivableModel);
      if (pageUrl) {
        let data = treeColumns.map(item => item.key)
        yield put({ type: "updateState", payload: { personalizedColumn: JSON.parse(JSON.stringify(data)), allData: JSON.parse(JSON.stringify(data)) } });
        yield put({ type: "getAllDictionaryValueNotPage", payload: "late_type" });
        yield put({ type: "getAllDictionaryValueNotPage", payload: "overdue_reason" });
        yield put({ type: "getAllDictionaryValueNotPage", payload: "start_count_node" });
        yield put({ type: "getAllAccountsReceivable", payload: { params: { isCancel: "1" }, flag: "accountsReceivableNum" } });
        yield put({ type: "getAllAccountsReceivable", payload: { params: { isCancel: "0" }, flag: "cancelAfterVerification" } });
        yield put({ type: "getAllAccountsReceivable", payload: { params: {}, flag: "allNum" } });
        yield put({ type: "functionalPermissionProcessing", payload: {} });
        yield put({ type: "customColumn", payload: { createId: JSON.parse(userInfo).id } });
        if (history.location.state) {
          if (history.location.state instanceof Array) {
            yield put({
              type: "getAllAccountsReceivable", payload: {
                params: { isCancel: "1", isOverdue: "0", homeJumpParam: history.location.state.join(',') },
                flag: "withinTimeLimitNum"
              }
            });
            yield put({ type: "getListDatas", payload: { params: { isCancel: "1", isOverdue: "0", homeJumpParam: history.location.state.join(',') } } });
          } else {
            yield put({ type: "getAllAccountsReceivable", payload: { params: { isCancel: "1", isOverdue: "0" }, flag: "withinTimeLimitNum" } });
            yield put({ type: "getListDatas", payload: { params: history.location.state } });
          }
        } else {
          yield put({ type: "getAllAccountsReceivable", payload: { params: { isCancel: "1", isOverdue: "0" }, flag: "withinTimeLimitNum" } });
          yield put({ type: "getListDatas", payload: { params: { isCancel: "1" } } });
        }
      }
    },
    //信用评估列表
    *getListDatas({ payload: { currentPage = 1, pageSize = config.PAGE_SIZE, params } }, { select, call, put }) {
      yield put({ type: "updateState", payload: { accountsReceivableLoading: true } });//
      const res = yield call(accountsReceivableService.getAllAccountsReceivable, { ...params, currentPage, pageSize, });
      if (res.code == "200") {
        yield put({
          type: 'updateState',
          payload: { accountsReceivableList: res.data.records, total: res.data.total, currentPage, pageSize },
        });
      } else {
        message.info("应收账款管理列表查询失败！");
      }
      yield put({ type: "updateState", payload: { accountsReceivableLoading: false } });
    },
    //信用评估列表
    *getAllAccountsReceivable({ payload: { currentPage = 1, pageSize = 10, params, flag } }, { select, call, put }) {
      const res = yield call(accountsReceivableService.getAllAccountsReceivable, { ...params, currentPage, pageSize, });
      if (res.code == "200") {
        switch (flag) {
          case 'accountsReceivableNum':
            yield put({ type: 'updateState', payload: { accountsReceivableNum: res.data.total, }, });//应收
            break;
          case 'withinTimeLimitNum':
            yield put({ type: 'updateState', payload: { withinTimeLimitNum: res.data.total, }, });//逾期
            break;
          case 'cancelAfterVerification':
            yield put({ type: 'updateState', payload: { cancelAfterVerification: res.data.total, }, });//回款
            break;
          case 'allNum':
            yield put({ type: 'updateState', payload: { allNum: res.data.total, }, });//全部
            break;
          // no default
        }
      }
    },
    // 下拉列表
    *getAllDictionaryValueNotPage({ payload: params }, { select, call, put }) {
      const res = yield call(accountsReceivableService.getAllDictionaryValueNotPage, { dictCode: params });
      if (res.code == 200) {
        switch (params) {
          case 'approval_status':
            yield put({ type: 'updateState', payload: { examinationApprovalStatus: res.data, }, }); //审批状态
            break;
          case 'late_type':
            yield put({ type: 'updateState', payload: { overdueTypeList: res.data, }, });
            break;
          case 'overdue_reason':
            let list = res.data;
            list.map((item, index) => {
              if (item.dictSubCode == 'accounts_not_settled') list.splice(index, 1)
            })
            yield put({ type: 'updateState', payload: { overdueReasonList: list }, });
            break;
          case 'start_count_node':
            yield put({ type: 'updateState', payload: { countNodeList: res.data, }, }); //付款起算节点
            break;
          // no default
        }
      }
    },
    //功能权限处理
    *functionalPermissionProcessing({ payload: params }, { select, put, call }) {
      //角色管理key:accountsReceivable
      let keyData = JSON.parse(sessionStorage.getItem("menuData")).list
      let key = keyData ? keyData.filter(item => item.key.indexOf("accountsReceivable") !== -1).map(item => item.key) : []
      yield put({ type: "updateState", payload: { menuData: key } });
    },
    //附件查看
    *selectAttachment({ payload: params }, { select, call, put }) {
      yield put({ type: 'updateState', payload: { attachmentUploadModalLoading: true }, });
      const res = yield call(accountsReceivableService.selectAttachment, params);
      if (res.code == "200") {
        yield put({ type: 'updateState', payload: { attachmentUploadModalList: res.data, attachmentUploadModalLoading: false }, });
      } else {
        message.info("附件查询失败！");
      }
    },
    //附件删除
    *deleteFileById({ payload: { params, data } }, { select, call, put }) {
      const res = yield call(accountsReceivableService.deleteFileById, params);
      if (res.code == 200) {
        message.info("删除成功！");
        yield put({ type: 'selectAttachment', payload: data });
      } else {
        message.info("删除失败！");
      }
    },
    //附件下载
    *downloadFile({ payload: params }, { select, call, put }) {
      yield call(accountsReceivableService.downloadFile, { id: params.id }, params.originalFileName);
    },
    //附件上传
    *uploadFile({ payload: { params, data } }, { select, call, put }) {
      const res = yield call(accountsReceivableService.uploadFile, params);
      if (res.code == 200) {
        message.info("上传成功！");
      } else {
        message.info(res.message);
      }
      yield put({ type: 'selectAttachment', payload: data });
    },
    //自定义列
    *customColumn({ payload: params }, { select, put, call }) {
      //角色管理key:accountsReceivable
      const res = yield call(homeService.getPersonalizedColumn, params);
      if (res.code == "200") {
        let list = res.data.filter(item => item.menuKey === "accountsReceivable")
        let data = list.length > 0 && list[0].menuFields
        data ? yield put({ type: 'updateState', payload: { personalizedColumn: data.split(",") }, }) : null
      }
    },
  },

  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(location => {
        if (location.pathname == "/scmp/credit/accountsReceivable") {
          dispatch({ type: 'init', payload: { history } });
        }
      });
    },
  },
};
